#!/usr/bin/python3
# -*-coding: utf-8-*-
# by QianFeng.newrain
#
"""
    Welcome QianFeng cloud computing
"""
import requests
import json
import sys
import time, hmac, base64, hashlib, urllib.parse


headers = {"Content-Type": "application/json;charset=utf-8"}
# 需要修改，钉钉群助手中获取
timestamp = str(round(time.time() * 1000))
# 需要修改
secret = "SEC40a5c5e8c3b198012baffb79f6ab50034d56ef3fdbee1ad72c301c86ce788a02"
secret_enc = secret.encode("utf-8")
string_to_sign = "{}\n{}".format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode("utf-8")
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
url="https://oapi.dingtalk.com/robot/send?access_token=26427125497568cf5ddc00dbdba819207553bd4da1e8ff19f089179007485d88"
api_url = f"{url}&timestamp={timestamp}&sign={sign}"


def msg(text):
    json_text = {
        "msgtype": "markdown",
        "at": {"atMobiles": ["all"], "isAtAll": False},
        "markdown": {"title": "zabbix告警", "text": text},
    }
    print(
        requests.post(api_url, json.dumps(json_text), headers=headers).content.decode()
    )


msg("\n" + sys.argv[1])
